package com.ytkj.ygAssist.server;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.ytkj.ygAssist.server.util.DateUtil;
import com.ytkj.ygAssist.server.util.HttpGetUtil;
import com.ytkj.ygAssist.server.util.JsonUtil;
import com.ytkj.ygAssist.tools.CacheData;
import com.ytkj.ygAssist.tools.Config;
import com.ytkj.ygAssist.tools.JFrameListeningInterface;
import com.ytkj.ygAssist.tools.MyLog;
import com.ytkj.ygAssist.tools.YungouDataTools;
import com.ytkj.ygAssist.view.MainJFrame;
import com.ytkj.ygAssist.view.NowWinning;
import com.ytkj.ygAssist.view.TrendChart;
import com.ytkj.ygAssist.view.VipAnalyze;
import com.ytkj.ygAssist.view.myView.BackgroundMonitor;
import com.ytkj.ygAssist.viewControl.ForeknowControl;
import com.ytkj.ygAssist.viewControl.IntelligentMonitoringControl;

import org.apache.http.impl.client.CloseableHttpClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GetUserBuyServer {
	public static HashMap<String, GetUserBuyServer> startThread = new HashMap<String, GetUserBuyServer>();
	private boolean isSelect = false;
	private String goodsID = null;// 商品ID
	private String codePeriod = null;// 购买期数
	private String codeID = null;// 网址ID
	private Integer index = 0;// 记录中奖位
	private Integer buyStartPosition = 0;// 购买起始位置
	private String codeRNO = null;// 中奖码
	private String userName = null;// 查询中奖人姓名
	private String winUserName = null;// 记录中奖人姓名
	private String buyNum = null;// 本期中奖人购买数量
	private boolean isFind = true;// 是否结束查询
	private CloseableHttpClient HttpClient = null;// 查询使用HTTPClient
	private int selectNum = 0;// 查询次数
	private String goodsKeyUserWeb = null;// 中奖人web

	private int userBuyListCount = 0;// 记录参与人数
	private boolean checkLastData = true;

	public static GetUserBuyServer getUserBuyServer(String codeID) {
		GetUserBuyServer getUserBuyServer = startThread.get(codeID);
		if (getUserBuyServer == null) {
			getUserBuyServer = new GetUserBuyServer();
			startThread.put(codeID, getUserBuyServer);
		} else {
			getUserBuyServer.isSelect = true;
		}
		return getUserBuyServer;
	}

	public static HashMap<String, GetUserBuyServer> getStartThread() {
		return startThread;
	}

	public GetUserBuyServer() {
		this.HttpClient = HttpGetUtil.createHttpClient();
	}

	public void setBarcodernoInfo(String codeRNO, String userName, String goodsKeyUserWeb) {
		this.codeRNO = codeRNO;
		this.winUserName = userName;
		this.goodsKeyUserWeb = goodsKeyUserWeb;
	}

	/*
	 * 查询商品期数是否存在 goodsID商品id period期数
	 */
	public void GetGoodsPeriodInfo(String goodsID, String codePeriod, String codeID, boolean codeState) {
		this.goodsID = goodsID;
		this.codePeriod = codePeriod;
		this.codeID = codeID;
		if (CacheData.getGoodsPriceCacheDate(goodsID) == null) {
			try {
//				CacheData.setGoodsPriceCacheDate(goodsID,
//						Integer.parseInt(GetGoodsInfo.shopCartNew(codeID, HttpClient)[3]));
//				CacheData.setGoodsPriceCacheDate(goodsID,
//						Integer.parseInt(GetGoodsInfo.shopCartNewByHtml(goodsID, HttpClient)[3]));
				CacheData.setGoodsPriceCacheDate(goodsID,
						Integer.parseInt(GetGoodsInfo.getGoodsSalingByGoodsID(goodsID, HttpClient)[3]));
			} catch (Exception e) {
				CallbackDataText("goodsoldOut", null);
				return;
			}
		}
		if (codeState) {
			try {
				Map<String, String> barcodernoInfo = GetGoodsInfo.getBarcodernoInfo(codeID);
				if (barcodernoInfo != null) {
					codeRNO = barcodernoInfo.get("codeRNO");
					winUserName = barcodernoInfo.get("userName");
					goodsKeyUserWeb = barcodernoInfo.get("userWeb");
					CacheData.addCodeRNOCacheDate(codeID, codeRNO);
				}
				// System.out.println("查询中奖码：" + codeRNO);
			} catch (Exception e) {
			}
		}
		String[] text = new String[] { goodsID, codePeriod, codeRNO == null ? "" : codeRNO,
				winUserName == null ? "" : winUserName, "", "", "", codeID };
		CallbackDataListeningText(text);
		if (isSelect) {
			MyLog.outLog("正在查", goodsID, codePeriod);
			return;
		}
		getCodeNum();
	}

	/*
	 * 获取中奖位置
	 */
	private void getCodeNum() {
		try {
			getUserBuyList(1);
			if (isFind) {
				if (CacheData.getGoodsPriceCacheDate(goodsID) > 8000) {
					CallbackDataText("isSelect", goodsID + "___" + codePeriod + "___" + codeID);
				}
				for (int i = 11; i <= userBuyListCount; i += 10) {
					getBarcodeInfo();
					if (userBuyListCount != CacheData.getUserBuyListCacheDate(codeID).size()) {
						getUserBuyList(i);
					}
				}
			}
		} catch (Exception e) {
			selectNum++;
			MyLog.outLog("获取中奖位置错误了", goodsID, codePeriod, "次数", selectNum);
			if (selectNum < 10) {
				index = 0;
				if (CacheData.getSelectCacheDate(goodsID, codePeriod) == null) {
					getCodeNum();
				} else {
					startThread.remove(codeID);
					CallbackDataListeningText(CacheData.getSelectCacheDate(goodsID, codePeriod));
				}
			} else {
				startThread.remove(codeID);
				CallbackDataText("webError", goodsID + "___" + codePeriod + "___" + codeID);
			}
		}

	}

	/*
	 * 获取参与记录
	 */
	private void getUserBuyList(int FIdx) {
		String content = null;
		if (CacheData.getSelectCacheDate(goodsID, codePeriod) == null) {
			if (isFind) {
				content = GetGoodsInfo.getUserBuyListEnd(codeID, FIdx, HttpClient);
				MyLog.outLog("查询到参与记录", goodsID, codePeriod, content);
				formatData(content, FIdx);
			}
		} else {
			startThread.remove(codeID);
			CallbackDataListeningText(CacheData.getSelectCacheDate(goodsID, codePeriod));
			isFind = false;
		}
	}

	/*
	 * 输出获取到的信息
	 */
	private void formatData(String content, int FIdx) {
		JsonArray data = null;
		try {
//			data = content.substring(content.indexOf("data\":") + 6, content.length() - 2);
//			JsonObject jsonObject = new Gson().fromJson(content, JsonObject.class);
			JsonObject jsonObject = JsonUtil.fromJsonClear(content, JsonObject.class);
			if("0".equals(jsonObject.get("code").toString())){
				data = jsonObject.getAsJsonArray("data");
				MyLog.testLog("数据", data);
			}
		} catch (Exception e) {
			MyLog.outLog("获取参与记录错误了", goodsID, codePeriod, "次数", selectNum);
			SelectAssistPublishs.getYungouPublishs(goodsID, codePeriod, "1");
			MyLog.threadSleep(3000);
			selectNum++;
			if (selectNum < 20) {
				getUserBuyList(FIdx);
			} else {
				isFind = false;
				startThread.remove(codeID);
				CallbackDataText("webError", goodsID + "___" + codePeriod + "___" + codeID);
			}
			return;
		}
		List<Map<String, String>> dList = new Gson().fromJson(data, new TypeToken<List<Map<String, String>>>() {
		}.getType());
		if (FIdx == 1) {
			userBuyListCount = getUserBuyListCount(content);
			if (codeRNO == null) {
				getCodeRNO(dList.get(0).get("buyID"),dList.get(0).get("buyTime"));
			}
		}
		for (Map<String, String> maps : dList) {
			if (CacheData.getSelectCacheDate(goodsID, codePeriod) == null) {
				buyNum = maps.get("buyNum");
				if (isFind) {
					if (goodsKeyUserWeb == null) {
						userName = maps.get("userName");
						String buyID = maps.get("buyID");
						String[] userBuyListCacheDate = CacheData.getUserBuyListCacheDate(codeID, buyID);
						if (userBuyListCacheDate == null) {
							String buyCode = getUserBuyCode(buyID);
							CacheData.setUserBuyListCacheDate(codeID, buyID,
									new String[] { buyNum, userName, maps.get("userWeb"), buyCode });
						} else {
							sortBuyCodeByCache(userBuyListCacheDate[3]);
						}
					} else {
						if (goodsKeyUserWeb.equals(maps.get("userWeb"))) {
							getUserBuyCode(maps.get("buyID"));
						} else {
							index = index + Integer.parseInt(buyNum);
						}
					}
				}
			} else {
				isFind = false;
				CallbackDataListeningText(CacheData.getSelectCacheDate(goodsID, codePeriod));
				return;
			}
		}

		if (codeRNO != null && userBuyListCount == CacheData.getUserBuyListCacheDate(codeID).size()) {
			// if (codeRNO != null && YungouDataTools.getCodeNum(codeID) ==
			// CacheData.getGoodsPriceCacheDate(goodsID)) {
			if (YungouDataTools.selectBarcodernoInfoByCache(goodsID, codePeriod, codeID, codeRNO, 0)) {
				if (CacheData.getSelectCacheDate(goodsID, codePeriod) != null) {
					isFind = false;
					startThread.remove(codeID);
					CallbackDataListeningText(CacheData.getSelectCacheDate(goodsID, codePeriod));
				}
			}
		}
		if (FIdx > 21) {
			try {
				int price = CacheData.getGoodsPriceCacheDate(goodsID);
				if (price > 70000) {
					Thread.sleep(10000);
				} else if (price > 20000) {
					Thread.sleep(5000);
				} else if (price > 8000) {
					Thread.sleep(3000);
				} else if (price > 5000) {
					Thread.sleep(1000);
				} else if (price > 2000) {
					Thread.sleep(500);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/*
	 * 获取总页数
	 */
	private int getUserBuyListCount(String content) {
//		String data = content.split("Count\":", 2)[1];
//		data = data.split(",\"Data", 2)[0];
		String data = content.substring(content.indexOf("count\":")+7,content.indexOf(",\"data"));
		return Integer.parseInt(data);
	}

	/*
	 * 获取用户云够码
	 */
	private String getUserBuyCode(String buyIP) {
		try {
			if (CacheData.getSelectCacheDate(goodsID, codePeriod) == null) {
				if (isFind) {
					String content = GetGoodsInfo.getUserBuyCode(codeID, buyIP);
					return sortBuyCode(content);
				}
			} else {
				startThread.remove(codeID);
				CallbackDataListeningText(CacheData.getSelectCacheDate(goodsID, codePeriod));
				isFind = false;
			}
		} catch (Exception e) {
			MyLog.outLog("获取用户云够码错误了", goodsID, codePeriod, "次数", selectNum);
			SelectAssistPublishs.getYungouPublishs(goodsID, codePeriod, "1");
			if (selectNum < 10) {
				selectNum++;
				return getUserBuyCode(buyIP);
			} else {
				isFind = false;
				startThread.remove(codeID);
				CallbackDataText("webError", goodsID + "___" + codePeriod + "___" + codeID);
			}
		}
		return null;
	}

	/*
	 * 输出云够码
	 */
	private String sortBuyCode(String content) {
		JsonObject jsonObject = JsonUtil.fromJsonClear(content, JsonObject.class);
		List<Map<String, String>> dList = new ArrayList<Map<String, String>>();
		if("0".equals(jsonObject.get("code").toString())){
			JsonArray data = jsonObject.getAsJsonArray("data");
			dList = new Gson().fromJson(data, new TypeToken<List<Map<String, String>>>() {}.getType());
		}
		buyStartPosition = index;
		StringBuffer sBuffer = new StringBuffer();
		for (Map<String, String> maps : dList) {
			if (maps.get("rnoNum").equals(codeRNO)) {
				isFind = false;
				int price2 = CacheData.getGoodsPriceCacheDate(goodsID);
				// 中奖区间
				String buySection = (price2 - buyStartPosition - Integer.parseInt(buyNum) + 1) + "~"
						+ (price2 - buyStartPosition);
				String buyPosition = Integer.toString(price2 - index);
				if (winUserName == null) {
					winUserName = userName;
				}
				String[] text = new String[] { goodsID, codePeriod, codeRNO, winUserName, buyNum, buyPosition,
						buySection, codeID };
				if (CacheData.getSelectCacheDate(goodsID, codePeriod) == null) {
					CallbackDataListeningText(text);
					CacheData.setSelectCacheDate(goodsID, codePeriod, text);
					SelectAssistPublishs.uploadYungouPublishs(text);
					CacheData.removeUserBuyListCacheDate(codeID);
					startThread.remove(codeID);
				}
				MyLog.outLog("直接查询到了位置：", goodsID, codePeriod, codeRNO, winUserName, buyPosition);
				HttpGetUtil.CloseHttpClient(HttpClient);
				break;
			}
			sBuffer.append(maps.get("rnoNum")).append(",");
			index++;
		}
		String ronNum = sBuffer.toString();
		return ronNum.substring(0, ronNum.length() - 1);
	}

	/*
	 * 输出云够码
	 */
	private void sortBuyCodeByCache(String content) {
		String[] buyCode = content.split(",");
		buyStartPosition = index;
		for (int i = 0; i < buyCode.length; i++) {
			if (buyCode[i].equals(codeRNO)) {
				isFind = false;
				int price2 = CacheData.getGoodsPriceCacheDate(goodsID);
				// 中奖区间
				String buySection = (price2 - buyStartPosition - buyCode.length + 1) + "~"
						+ (price2 - buyStartPosition);
				String buyPosition = Integer.toString(price2 - index);
				if (winUserName == null) {
					winUserName = userName;
				}
				String[] text = new String[] { goodsID, codePeriod, codeRNO, winUserName,
						Integer.toString(buyCode.length), buyPosition, buySection, codeID };
				if (CacheData.getSelectCacheDate(goodsID, codePeriod) == null) {
					CallbackDataListeningText(text);
					CacheData.setSelectCacheDate(goodsID, codePeriod, text);
					SelectAssistPublishs.uploadYungouPublishs(text);
					CacheData.removeUserBuyListCacheDate(codeID);
					startThread.remove(codeID);
				}
				MyLog.outLog("查到ByCache位置：", goodsID, codePeriod, codeRNO, winUserName, buyPosition);
				HttpGetUtil.CloseHttpClient(HttpClient);
				break;
			}
			index++;
		}
	}

	/*
	 * 获取中奖码
	 */
	private void getCodeRNO(final String buyID, final String buyTime) {
		MyLog.outLog("正在查询中奖码", goodsID, codePeriod, buyTime);
		// time = System.currentTimeMillis();
		new Thread(new Runnable() {
			public void run() {
				long buyTimeLong = DateUtil.getTimeLong(buyTime);
				String sBuyTime = buyTime;
				while (CacheData.getCodeRNOCacheDate(codeID) == null) {
					if ((Config.yungouTime - buyTimeLong) > 10000) {
						if (checkLastData) {
							checkLastData = false;
							if ((Config.yungouTime - buyTimeLong) < 180000) {
								MyLog.outLog("检查最后一条记录查询是否错误", goodsID, codePeriod, buyTime);
								try {
									String content = GetGoodsInfo.getUserBuyListEnd(codeID, 1, HttpClient);
									if (getUserBuyListCount(content) > userBuyListCount) {
										MyLog.outLog("最后一条记录查询错误", goodsID, codePeriod, buyTime);
										isFind = false;
										index = 0;
										startThread.remove(codeID);
										GetUserBuyServer.getUserBuyServer(codeID).GetGoodsPeriodInfo(goodsID,
												codePeriod, codeID, false);
										return;
									}
								} catch (Exception e) {
								}
							}
						}
						// time = System.currentTimeMillis();
						codeRNO = GetHistoryBuyRecord.getCodeRNO(buyID,sBuyTime,
								CacheData.getGoodsPriceCacheDate(goodsID).toString());
						if (codeRNO != null) {
							// MyLog.outLog("查询中奖码用时", goodsID, codePeriod,
							// System.currentTimeMillis() - time);
							MyLog.outLog("查询到中奖码", goodsID, codePeriod, codeRNO);
							CacheData.addCodeRNOCacheDate(codeID, codeRNO);
							String[] text = new String[] { goodsID, codePeriod, codeRNO, "", "", "", "", codeID };
							CallbackDataListeningText(text);
							Integer isAll = userBuyListCount == CacheData.getUserBuyListCacheDate(codeID).size() ? 0
									: index;
							if (YungouDataTools.selectBarcodernoInfoByCache(goodsID, codePeriod, codeID, codeRNO,
									isAll)) {
								if (CacheData.getSelectCacheDate(goodsID, codePeriod) != null) {
									isFind = false;
									startThread.remove(codeID);
									CallbackDataListeningText(CacheData.getSelectCacheDate(goodsID, codePeriod));
								}
							}
						} else {
							MyLog.outLog("查询中奖码错误了", goodsID, codePeriod);
							getBarcodeInfo();
							MyLog.threadSleep(1000);
						}
					} else {
						MyLog.outLog("服务器时间未到");
						MyLog.threadSleep(1000);
					}
				}
			}
		}).start();
	}

	private void getBarcodeInfo() {// 获取中奖信息
		if (goodsKeyUserWeb == null) {
			boolean isCodeRNO = (codeRNO == null);
			try {
				List<Map<String, String>> list = GetGoodsInfo.getBarcodeRaffListByGoodsID(goodsID, "5");
				for (Map<String, String> map : list) {
					if (map.get("codeID").equals(codeID) && !map.get("codeRNO").equals("")) {
						this.codeRNO = map.get("codeRNO");
						this.winUserName = map.get("userName");
						this.goodsKeyUserWeb = map.get("userWeb");
						CacheData.addCodeRNOCacheDate(codeID, codeRNO);
						return;
					}
				}
				Map<String, String> barcodernoInfo = GetGoodsInfo.getBarcodernoInfo(codeID);
				if (barcodernoInfo != null) {
					codeRNO = barcodernoInfo.get("codeRNO");
					winUserName = barcodernoInfo.get("userName");
					goodsKeyUserWeb = barcodernoInfo.get("userWeb");
					CacheData.addCodeRNOCacheDate(codeID, codeRNO);
				}
				// System.out.println("查询中奖码：" + codeRNO);
			} catch (Exception e) {
				MyLog.outLog("获取中奖信息错误了", goodsID, codePeriod);
			}
			if (goodsKeyUserWeb != null) {
				String[] text = new String[] { goodsID, codePeriod, codeRNO, winUserName, "", "", "", codeID };
				CallbackDataListeningText(text);
				if (isCodeRNO) {
					Integer isAll = userBuyListCount == CacheData.getUserBuyListCacheDate(codeID).size() ? 0 : index;
					if (YungouDataTools.selectBarcodernoInfoByCache(goodsID, codePeriod, codeID, codeRNO, isAll)) {
						if (CacheData.getSelectCacheDate(goodsID, codePeriod) != null) {
							isFind = false;
							startThread.remove(codeID);
							CallbackDataListeningText(CacheData.getSelectCacheDate(goodsID, codePeriod));
						}
					}
				}
			}
		}
	}

	private void CallbackDataListeningText(String[] text) {
		JFrameListeningInterface[] jFrameListening = getViewJFrameListeningInterface();
		for (int i = 0; i < jFrameListening.length; i++) {
			if (jFrameListening[i] != null) {
				jFrameListening[i].setFrameListeningText("3", text);
			}
		}
	}

	private void CallbackDataText(String FrameName, String text) {
		JFrameListeningInterface[] jFrameListening = getViewJFrameListeningInterface();
		for (int i = 0; i < jFrameListening.length; i++) {
			if (jFrameListening[i] != null) {
				jFrameListening[i].setFrameText(FrameName, text);
			}
		}
	}

	private JFrameListeningInterface[] getViewJFrameListeningInterface() {
		JFrameListeningInterface[] jFrameListening = new JFrameListeningInterface[6];
		// 智能监听回调
		jFrameListening[0] = ((IntelligentMonitoringControl) MainJFrame.getMainJFrame().getTabbedPaneSelected(1))
				.getJFrameListeningInterface();
		// 提前揭晓回调
		jFrameListening[1] = ((ForeknowControl) MainJFrame.getMainJFrame().getTabbedPaneSelected(2))
				.getJFrameListeningInterface();
		// 走势分析回调
		jFrameListening[2] = ((TrendChart) MainJFrame.getMainJFrame().getTabbedPaneSelected(3))
				.getJFrameListeningInterface();
		// 马上开奖回调
		jFrameListening[3] = ((NowWinning) MainJFrame.getMainJFrame().getTabbedPaneSelected(4))
				.getJFrameListeningInterface();
		// vip预测
		if (Config.isVip) {
			jFrameListening[4] = ((VipAnalyze) MainJFrame.getMainJFrame().getTabbedPaneSelected(8))
					.getJFrameListeningInterface();
		}
		if (Config.isServerVersions) {
			jFrameListening[5] = ((BackgroundMonitor) MainJFrame.getMainJFrame().getTabbedPaneSelected(9))
					.getJFrameListeningInterface();
		}
		return jFrameListening;
	}
}
